﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: Sample.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-26 4:21 PM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;

namespace BOL.Linq.Probability
{
    public static partial class Probability
    {
        public static TKey Sample<TKey>(this IDictionary<TKey, double> probabilityTable, Random r)
        {
            probabilityTable.Normalize();

            var roll = r.NextDouble();
            var temp = 0.0;
            foreach (var key in probabilityTable.Keys)
            {
                temp += probabilityTable[key];
                if (roll <= temp)
                    return key;
            }

            return default(TKey);
        }
    }
}
